package com.xinguan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinguan.dao.TbDepartmentDao;
import com.xinguan.dao.TbUserDao;
import com.xinguan.entity.TbDepartment;
import com.xinguan.entity.TbUser;
import com.xinguan.error.SystemCodeEnum;
import com.xinguan.error.SystemException;
import com.xinguan.response.ResponseBean;
import com.xinguan.service.TbDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinguan.vo.system.DepartmentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 郭经伟
 * @since 2021-07-11
 */
@Service
public class TbDepartmentServiceImpl extends ServiceImpl<TbDepartmentDao, TbDepartment> implements TbDepartmentService {


    @Resource
    private TbDepartmentDao departmentDao;

    @Resource
    private TbUserDao userDao;

    /**
     * 查询部门列表
     * @param currentPage
     * @param pageSize
     * @param departmentName
     * @return
     */
    @Override
    public ResponseBean findDepartmentList(Integer currentPage, Integer pageSize, String departmentName) {
        // 先分页查询出所有的部门列表
        Page<TbDepartment> departmentPage = departmentDao.selectPage(new Page<TbDepartment>(currentPage, pageSize), null);
        long total = departmentPage.getTotal();
        List<TbDepartment> records = departmentPage.getRecords();
        List<DepartmentVO> myRecords=new ArrayList<>();
        // 进行部门人数统计
        records.forEach(department->{
            Integer count = userDao.selectCount(new QueryWrapper<TbUser>().eq("department_id", department.getId()));
            DepartmentVO departmentVO = new DepartmentVO();
            BeanUtils.copyProperties(department,departmentVO);
            departmentVO.setTotal(count);
            myRecords.add(departmentVO);
        });
        Page<DepartmentVO> departmentVOPage = new Page<DepartmentVO>();
        departmentVOPage.setCurrent(currentPage);
        departmentVOPage.setSize(pageSize);
        departmentVOPage.setTotal(total);
        departmentVOPage.setRecords(myRecords);
        return ResponseBean.success(departmentVOPage);
    }

    /**
     * 新增部门
     * @param departmentVO
     */
    @Transactional
    @Override
    public void addDepartment(DepartmentVO departmentVO) throws SystemException {
        // 先判断当前部门名是否存在
        @NotBlank(message = "院系名称不能为空") String name = departmentVO.getName();
        TbDepartment tbDepartment = departmentDao.selectOne(new QueryWrapper<TbDepartment>().eq("name", name));
        if (tbDepartment!=null){
            // 当前部门已存在
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"部门已存在");
        }
        TbDepartment department = new TbDepartment();
        BeanUtils.copyProperties(departmentVO,department);
        department.setCreateTime(new Date());
        department.setModifiedTime(new Date());
        departmentDao.insert(department);
    }

    @Transactional
    @Override
    public void deleteDepartment(Long id) throws SystemException {

        // 先判断当前部门是否存在
        TbDepartment tbDepartment = departmentDao.selectById(id);
        if (tbDepartment==null){
            // 当前删除的部门不存在
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"当前删除的部门已存在");
        }
        departmentDao.deleteById(id);
    }

    @Override
    public DepartmentVO edit(Long id) throws SystemException {
        TbDepartment tbDepartment = departmentDao.selectById(id);
        if (tbDepartment==null){
            // 当前编辑的部门不存在
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"当前编辑的部门不存在");
        }
        DepartmentVO departmentVO = new DepartmentVO();
        BeanUtils.copyProperties(tbDepartment,departmentVO);
        return departmentVO;
    }

    @Transactional
    @Override
    public void updateDepartment(Long id, DepartmentVO departmentVO) throws SystemException {

        @NotBlank(message = "院系名称不能为空") String name = departmentVO.getName();
        TbDepartment tbDepartment = departmentDao.selectById(id);
        if (tbDepartment==null){
            // 当前编辑的部门不存在
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"当前编辑的部门不存在");
        }
        // 判断当前name是否存在
        TbDepartment department = departmentDao.selectOne(new QueryWrapper<TbDepartment>().eq("name", name));
        if (department!=null){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"部门已存在");
        }
        // 更新
        departmentDao.update(null,new UpdateWrapper<TbDepartment>().
                eq("id",id).
                set("name",name).
                set("phone",departmentVO.getPhone()).
                set("address",departmentVO.getAddress())
                .set("modified_time",new Date()));

    }

    @Override
    public ResponseBean findAllDepartmentNames() {
        List<DepartmentVO> departmentVOS=new ArrayList<>();
        List<TbDepartment> departments = departmentDao.selectList(null);
        departments.forEach(department->{
            Integer count = userDao.selectCount(new QueryWrapper<TbUser>().eq("department_id", department.getId()));
            DepartmentVO departmentVO = new DepartmentVO();
            departmentVO.setName(department.getName());
            departmentVO.setTotal(count);
            departmentVO.setId(department.getId());
            departmentVOS.add(departmentVO);
        });
        return ResponseBean.success(departmentVOS);
    }
}
